package com.example.emos.wx.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2023/8/9
 */
@Configuration
public class ThreadPoolConfig {
    @Bean("AsyncTaskExecutor")
    public AsyncTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数，与CPU的核心数有关
        executor.setCorePoolSize(4);
        //设置最大线程数，与CPU的核心数有关，一般取两倍即可
        executor.setMaxPoolSize(8);
        //设置队列容量
        executor.setQueueCapacity(16);
        //设置线程活跃时间，单位秒
        executor.setKeepAliveSeconds(60);
        //设置默认线程名称前缀
        executor.setThreadNamePrefix("task-");
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化线程池
        executor.initialize();
        return executor;
    }
}
